<?php


namespace app\common\service;


use app\admin\model\Staff;
use app\sys\service\GateCli;

class StaffService
{
    /**
     * 客服在线列表
     */
    public function StaffOnlineList($data)
    {
        $limit = $data['limit'] ?? PaginateService::LIMIT_DEFAULT;
        $list = Staff::alias('s')
            ->field('s.id,s.staff_no,s.name,s.staff_name,s.mobile,s.on_status,s.login_time,s.duty_name,s.status'
                . ',' .
                "ifNull(it.name,'') as team_name"
            )
            ->leftJoin("ic_team it", "it.id = s.team_id")
            ->where("s.status", "<", 3)
            ->paginate($limit);

        if (!empty($list)) $list->getCollection()->map(function ($list) {
            $list->on_status_text = Staff::$on_status_map[$list->on_status] ?? "";
            $list->status_text = Staff::$status_map[$list->status] ?? "";
            return $list;
        });
        PaginateService::appendBackstageResponseData($list);
        return $list;
    }

    /**
     * 自动关闭不在线的员工
     */
    public static function autoCloseNoOnline()
    {
        $prefix = GateCli::$staPre; //获取拼接前缀
        $list = Staff::where("status", "<", Staff::STATUS_LEAVE)->column("CONCAT('$prefix',staff_no) as staff_no");
        GateCli::$registerAddress = \think\facade\Env::get("GATEWAY.REGIS_ADDRESS");//text地址
        $arr = array_values(GateCli::getAllUidList());//获取全局在线uid列表
        $diff_arr = array_diff($list, $arr);//比较多余多余的数据
        if (empty($diff_arr)) return true;
        $diff_arr = array_map(function ($data) use ($prefix) {
            return str_replace("$prefix", "", $data);
        }, $diff_arr);
        Staff::whereIn('staff_no', $diff_arr)->update(['status' => Staff::STATUS_LEAVE]);//执行更新
        return true;
    }
}